package com.hk.blog.controller;

import com.hk.blog.domain.Role;
import com.hk.blog.service.PermissionService;
import com.hk.blog.service.RolePermissionService;
import com.hk.blog.service.RoleService;
import com.hk.blog.vo.RolePermBean;
import com.hk.commons.JsonResult;
import com.hk.commons.query.Order;
import com.hk.commons.query.QueryModel;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * @author Kevin
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("role")
public class RoleController {

    private final RoleService roleService;

    private final RolePermissionService rolePermissionService;

    private final PermissionService permissionService;

    @PostMapping("list")
    public JsonResult<?> list(@RequestBody QueryModel<Role> query) {
        if (query.getOrders().isEmpty()) {
            query.addOrders(Order.desc("createdDate"));
        }
        return JsonResult.success(roleService.queryForPage(query));
    }

    @GetMapping("get")
    public JsonResult<?> get(@RequestParam(required = false) Long id) {
        Map<String, Object> result = new HashMap<>();
        var permList = permissionService
                .findAll(Order.desc("lastModifiedDate")).stream()
                .map(item ->
                        Map.of("key", Objects.requireNonNull(item.getId()), "title",
                                String.format("(%s) - (%s)", item.getPermissionCode(), item.getPermissionName()))
                ).toList();
        result.put("permList", permList);
        if (Objects.nonNull(id)) {
            result.put("role", roleService.findById(id).orElse(null));
            result.put("permIds", rolePermissionService.findPermissionIdsByRoleId(id));
        }
        return JsonResult.success(result);
    }

    @PostMapping("delete")
    public JsonResult<?> deleteById(Long id) {
        roleService.deleteById(id);
        return JsonResult.success();
    }

    @PostMapping("save")
    public JsonResult<?> saveOrUpdate(@RequestBody RolePermBean role) {
        roleService.insertOrUpdate(role);
        return JsonResult.success();
    }
}

